package com.usian.behavior.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.usian.behavior.mapper.ApBehaviorEntryMapper;
import com.usian.behavior.mapper.ApLikesBehaviorMapper;
import com.usian.behavior.service.ApBehaviorEntryService;
import com.usian.behavior.service.ApLikesBehaviorService;
import com.usian.common.exception.CatchCustomException;
import com.usian.common.exception.code.UserStatusCode;
import com.usian.model.behavior.dtos.LikesBehaviorDto;
import com.usian.model.behavior.pojos.ApBehaviorEntry;
import com.usian.model.behavior.pojos.ApLikesBehavior;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.user.pojos.ApUser;
import com.usian.utils.threadlocal.AppThreadLocalUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class ApLikesBehaviorServiceImpl extends ServiceImpl<ApLikesBehaviorMapper, ApLikesBehavior> implements ApLikesBehaviorService {

    @Autowired
    private ApBehaviorEntryService apBehaviorEntryService;

    @Override
    public ResponseResult like(LikesBehaviorDto dto) {
        //1.检查参数
        if(dto == null || dto.getArticleId() == null || (dto.getType() < 0 && dto.getType() > 2) || (dto.getOperation() < 0 && dto.getOperation() > 1)){
            CatchCustomException.catchs(UserStatusCode.PARAM_FAIL,"参数有误");
        }
        // 查询行为实体  如何获取行为实体 根据当前登录的用户Id  获取行为实体对象
        ApUser apUser = AppThreadLocalUtils.getUser();
        ApBehaviorEntry entry =  apBehaviorEntryService.findByUserIdOrEquipmentId(apUser.getId(), dto.getEquipmentId());
        if(entry==null){
            CatchCustomException.catchs(UserStatusCode.PARAM_FAIL,"无法记录点赞行为");
        }
        // 查询是否点过赞 如果点过 并且是 取消点赞
        ApLikesBehavior apLikesBehavior = getOne(Wrappers.<ApLikesBehavior>lambdaQuery().eq(ApLikesBehavior::getArticleId, dto.getArticleId()).eq(ApLikesBehavior::getEntryId, entry.getId()));
        //2. 点赞或取消点赞 0 点赞 1 取消点赞
        if(apLikesBehavior == null && dto.getOperation() == 0){
            // 记录
            apLikesBehavior = new ApLikesBehavior();
            apLikesBehavior.setOperation(dto.getOperation());
            apLikesBehavior.setArticleId(dto.getArticleId());
            apLikesBehavior.setEntryId(entry.getId());
            apLikesBehavior.setType(dto.getType());
            apLikesBehavior.setCreatedTime(new Date());
            this.save(apLikesBehavior);
        }else if(apLikesBehavior !=null && dto.getOperation() == 1){
            // 取消点赞
            apLikesBehavior.setOperation(dto.getOperation());
            updateById(apLikesBehavior);
        }

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

}
